package com.unicom.network;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.unicom.config.StoryCore;
import com.unicom.request.GetCommentRequest;
import com.unicom.response.CommentModel;
import com.unicom.response.GetCommentResponse;
import com.unicom.utils.Utils;

import android.content.Context;
import android.util.Log;

public class JSONProtocol implements IStoryProtocol{
	String TAG = "JSONProtocol";
	private DefaultHttpClient httpclient;
	private Context context;
	private static final String AUTHENKEY = "AuthKey";

	public JSONProtocol(Context context, StoryCore core) {
		this.context = context;
	}
	
	private synchronized String getDataServerPost(String url, String data)throws ClientProtocolException, IOException {
		String responseStr = "";
		StringBuilder builder = new StringBuilder();
		HttpClient httpClient = new DefaultHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(data, HTTP.UTF_8);
			httpPost.setEntity(se);
			httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
			httpPost.setHeader("Security-Code","YgO455jStiyB810F5k8zG4DicEwsYakbJBf4x1Rvnxlge+Th0PDgf/peGKUFKIUtLQm590ILDgUr10LTLSwD8A");
			HttpResponse httpRes = null;
			try {
				httpRes = httpClient.execute(httpPost);
			} catch (Exception e) {
				Log.e("TAGGGGGG", e.toString());
			}
			
			if (httpRes.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpRes.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content), 8192);
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				responseStr = builder.toString();
			}
		} catch (ConnectTimeoutException e) {
			Log.e("JSONProtocol 1070", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketTimeoutException e) {
			Log.e("JSONProtocol 1073", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketException e) {
			Log.e("JSONProtocol 1076", e.getMessage());
			throw new ClientProtocolException();
		} catch (UnsupportedEncodingException e) {
			Log.e("JSONProtocol 1079", e.getMessage());
			throw new ClientProtocolException();
		} catch (ClientProtocolException e) {
			Log.e("JSONProtocol 1082", e.getMessage());
			throw e;
		}
		return responseStr;

	}

	@Override
	public GetCommentResponse getComment(GetCommentRequest request)throws JSONException, ClientProtocolException, IOException {
		GetCommentResponse response = new GetCommentResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GET_COMMENT);
		requestObject.put(AUTHENKEY, request.getAuthenKey());
		requestObject.put("Schedule_id", request.getSchedule_id());
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("pageNumber", request.getPageNumber());
		Log.e(TAG + " " + METHOD_GET_COMMENT,"content=" + requestObject.toString());
		String strResponse = getDataServerPost(URL,"content=" + requestObject.toString());
		Log.e(TAG + " " + METHOD_GET_COMMENT, strResponse);
		JSONObject responseObj = new JSONObject(strResponse);
		response.setReturnCode(responseObj.getInt("resultCode"));
		response.setResultMsg(responseObj.getString("resultMsg"));

		ArrayList<CommentModel> listComment = new ArrayList<CommentModel>();
		if (response.getReturnCode() == IStoryProtocol.STATUS_CODE_OK) {
			response.setCountPage(responseObj.getInt("countPage"));
			response.setRecordNumber(responseObj.getInt("recordNumber"));
			JSONArray jsonArray = responseObj.getJSONArray("data");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obj = jsonArray.getJSONObject(i);
				CommentModel commentModel = parserComment(obj);
				listComment.add(commentModel);
			}
			response.setListComment(listComment);
		}
		return response;
	}
	
	private CommentModel parserComment(JSONObject object) {
		CommentModel commentModel = new CommentModel();
		String value = "";
		value = object.optString("Schedule_id");
		commentModel.setSchedule_id(Utils.validateValue(value));
		value = object.optString("Schedule_name");
		commentModel.setSchedule_name(Utils.validateValue(value));
		value = object.optString("Title");
		commentModel.setTitle(Utils.validateValue(value));
		value = object.optString("Content");
		commentModel.setContent(Utils.validateValue(value));
		value = object.optString("Comment_date");
		commentModel.setComment_date(Utils.validateValue(value));
		value = object.optString("User_id");
		commentModel.setUser_id(Utils.validateValue(value));
		value = object.optString("UserName");
		commentModel.setUserName(Utils.validateValue(value));
		value = object.optString("Group_id");
		commentModel.setGroup_id(Utils.validateValue(value));
		value = object.optString("Fullname");
		commentModel.setFullname(Utils.validateValue(value));
		return commentModel;
	}
}
